package org.iabako.client.ui.page.business.sale;

import com.google.gwt.user.client.Timer;
import org.iabako.client.config.page.PageConfigEnum;
import org.iabako.client.config.page.PageTagItemEnum;
import org.iabako.client.navigation.NavigationController;
import org.iabako.client.tools.IabakoAsyncCallback;
import org.iabako.client.ui.form.AbstractForm;
import org.iabako.client.ui.form.business.client.ClientForm;
import org.iabako.client.ui.form.business.sale.SaleModifyForm;
import org.iabako.shared.entity.business.AbstractEntity;
import org.iabako.shared.entity.business.Sale;
import org.iabako.shared.entity.enumeration.PaymentType;
import org.iabako.shared.tools.GenericTools;

/**
 * Created by jose on 26/08/14.
 */
public class SaleModify extends SaleModifyForm {

    public SaleModify(AbstractForm abstractForm) {
        super(PageConfigEnum.SaleModify, "");

        this.parentForm = abstractForm;

        if (parentForm != null) {
            popup.timerAfterClosePopupAnimation = new Timer() {
                public void run() {
                    NavigationController.getInstance().closePopup(simplePopup);
                    NavigationController.getInstance().goTo(parentForm);
                    ((ClientForm) parentForm).refreshSales();
                }
            };
        }

        final String[] params = NavigationController.getInstance().getParams();

        saleServiceAsync.getById(Long.parseLong(params[0]), new IabakoAsyncCallback<AbstractEntity>() {
            public void onSuccess(AbstractEntity result) {
                if (result == null) {
                    NavigationController.getInstance().closePopup(simplePopup);
                    super.onSuccess(result);
                    return;
                }
                setSale((Sale) result);
                if (params.length > 1 && !GenericTools.isEmpty(params[1]) && "fromSaleCreation".equals(params[1])) {
                    if (((Sale) result).getPaymentType() == PaymentType.installments) {
                        salePaymentsForm.messages.showSuccessMessage("validation_sale_form_create_success_with_installments");
                    } else {
                        popup.setSelectedTag(PageTagItemEnum.SaleInvoice);
                        saleInvoiceForm.messages.showSuccessMessage("validation_sale_form_create_success");
                    }
                }
                super.onSuccess(result);
            }
        });
    }
}
